<template>
  <basic-container>
    <el-tabs v-model="activeName" style="margin: 0 10px" @tab-click="handleTabClick">
      <el-tab-pane label="原材料" name="material"></el-tab-pane>
      <el-tab-pane label="成品/半成品" name="progress"></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.partmaster_add" @click="addBtn">新增 </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.partmaster_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.partmaster_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.partmaster_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
        <el-button
          v-if="activeName === 'material' && permission.enableOrDisable"
          icon="el-icon-circle-check"
          size="small"
          type="text"
          @click.stop="handleEnableOrDisable(row, row.status)"
          v-preventReClick
          >{{ row.status === 1 ? '禁用' : '启用' }}
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="status">
        <el-tag :class="row.status === 1 ? 'successTag' : 'dangerTag'">{{ row.status === 1 ? '启用' : '禁用' }}</el-tag>
      </template>
      <template slot-scope="{ row }" slot="categoryId">
        <span v-if="row.categoryId !== null">{{ row.categoryName }}</span>
      </template>
    </avue-crud>

    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" @close="handleClose" :destroy-on-close="true" :append-to-body="true" top="5vh">
      <div class="sail-header-dialog-content">
        <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>基础信息</h3>
        <avue-form :option="formOption" v-model="formData" ref="formRef"></avue-form>
        <h3 v-if="activeName === 'material'" class="custom-title"><i class="el-icon-vertical-bar mr10"></i>品牌信息</h3>
        <avue-crud
          v-if="activeName === 'material'"
          :option="brandInfoOption"
          v-model="brandInfoForm"
          :data="brandData"
          ref="brandCrud"
          :before-open="brandBeforeOpen"
          @row-update="brandRowUpdate"
          @row-save="brandRowSave"
          @row-del="brandRowDel"
          :key="timer2"
        >
        </avue-crud>
        <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>扩展属性</h3>
        <avue-form :option="customizedFormOption" v-model="customizedForm" ref="customizedFormRef"></avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button type="primary" size="small" @click="handleConfirm"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getPartType, getInspection, updateStatus, testCriterion, deleteCriterion, getCategory } from '@/api/admin/partmaster';

import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config';
export default {
  name: 'AdminPartmaster',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [],
  data() {
    return {
      pageCode: 'ADMIN_PARAMASTER',
      activeName: 'material',
      dialogVisible: false,
      title: '新增原材料',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      brandInfoForm: {},
      formData: {},
      formOption: {
        labelWidth: 120,
        submitBtn: false,
        emptyBtn: false,
        submitText: '提交',
        column: []
      },
      brandData: [],
      brandInfoOption: {
        height: '300',
        calcHeight: 30,
        searchShow: true,
        border: true,
        index: true,
        selection: false,
        addBtn: true,
        viewBtn: false,
        editBtn: true,
        delBtn: true,
        tip: false,
        indexLabel: '序号',
        menuWidth: 150,
        dialogWidth: '50%',
        column: [
          {
            label: '供应商',
            prop: 'vendorName',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openVendorCommonModal();
            }
          },
          {
            label: '物料品牌',
            prop: 'partBrand',
            rules: [{ required: true, message: '请输入物料品牌', trigger: 'blur' }]
          },
          {
            label: '物料型号',
            prop: 'partModel',
            rules: [{ required: true, message: '请输入物料型号', trigger: 'blur' }]
          },
          {
            label: '单价(元)',
            prop: 'unitPrice',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value != '' && value != null) {
                    if (value <= 0) {
                      callback(new Error('单价不能小于等于0'));
                    } else {
                      callback();
                    }
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            display: false
          }
        ]
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 466px)',
        calcHeight: 30,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        selection: true,
        dialogClickModal: false,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        indexLabel: '序号',
        menuWidth: 250,
        columnBtn: false,
        column: [
          {
            label: '类别',
            prop: 'categoryId',
            searchSpan: 6,
            search: true,
            type: 'tree',
            dicData: this.categories,
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            searchSpan: 6,
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            searchSpan: 6,
            search: true
          },
          {
            label: '型号',
            prop: 'partModel',
            searchSpan: 6,
            search: true,
            hide: true
          },
          {
            label: '创建时间',
            prop: 'createTime'
          },
          {
            label: '状态',
            prop: 'status',
            align: 'center',
            slot: true
          }
        ]
      },
      categories: [],
      data: [],
      timer: new Date().getTime(),
      timer2: new Date().getTime(),
      tableOption: {},
      modalName: '',
      customizedFormOption: {
        labelWidth: 120,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '项目代码',
            prop: 'PrdID'
          },
          {
            label: '生产代码',
            prop: 'ItemID'
          }
        ]
      },
      customizedForm: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.partmaster_add, false),
        viewBtn: this.vaildData(this.permission.partmaster_view, false),
        delBtn: this.vaildData(this.permission.partmaster_delete, false),
        editBtn: this.vaildData(this.permission.partmaster_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  async created() {
    await this.fetchCategories();
    const tableColumn = this.findObject(this.option.column, 'categoryId');
    tableColumn.dicData = this.categories;
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    async fetchCategories() {
      try {
        // 发起请求获取物料类别数据
        const res = await getCategory();
        // 将获取的数据保存在组件的 data 中
        this.categories = res.data.data || [];
      } catch (error) {
        // 如果请求失败，输出错误信息
        console.error(error);
        // 可以根据实际情况进行错误处理，例如显示错误提示
      }
    },
    addBtn() {
      this.title = this.activeName === 'material' ? '新增原材料' : '新增成品/半成品';
      this.openDialog();
    },
    async rowUpdate(row) {
      try {
        this.title = this.activeName === 'material' ? '编辑原材料' : '编辑成品/半成品';
        const res = await getDetail(row.id);
        const from = res.data.data || {};
        if (from.customizedFields && from.customizedFields !== null) {
          this.customizedForm = JSON.parse(from.customizedFields);
        }
        this.formData = from;
        if (this.activeName === 'material') {
          this.brandData = this.formData.partBrandList;
        }
        this.openDialog();
      } catch (e) {
        console.log(e);
      }
    },
    async handleEnableOrDisable(row, status) {
      status === 1 ? (row.status = 2) : (row.status = 1);
      try {
        const res = await updateStatus(row);
        this.$message.success('操作成功');
      } catch (e) {
        console.log(e);
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    // 关闭弹窗
    handleClose() {
      this.$refs.formRef && this.$refs.formRef.resetForm();
      this.formData = {};
      this.brandData = [];
      this.$refs.customizedFormRef.resetForm();
      this.customizedForm = {};
      this.dialogVisible = false;
    },
    // 确认操作
    handleConfirm() {
      try {
        this.$refs.formRef.validate(async (valid, done) => {
          if (valid) {
            if (this.activeName === 'material' && this.brandData.length === 0) {
              this.$message.warning('请添加品牌信息！');
              done();
              return;
            }
            // 调用提交表单方法
            await this.handleSubmit();
          } else {
            // 如果表单验证不通过，不执行提交操作
            return false;
          }
          done();
        });
      } catch (e) {
        console.log(e);
      }
    },
    async handleSubmit() {
      try {
        const data = this._cloneDeep(this.formData);
        if (this.activeName === 'material') {
          data.partType = 'MATERIAL';
          data['partBrandList'] = this.brandData;
        }
        if (this.title.includes('新增')) {
          delete data.id;
        }
        data['customizedFields'] = JSON.stringify(this.customizedForm);
        await add(data);
        this.$message.success('添加成功');
        this.$refs.formRef.resetForm();
        this.handleClose();
        this.onLoad(this.page);
      } catch (e) {
        console.log(e);
      }

      // 提交成功后关闭弹窗
    },
    // 打开弹窗
    openDialog() {
      this.dialogVisible = true;
      if (this.activeName === 'material') {
        this.formOption.column = [
          {
            label: '物料类别',
            prop: 'categoryId',
            type: 'tree',
            dicData: [],
            props: {
              label: 'title',
              value: 'id'
            },
            change: ({ value, column }) => {
              if (value) {
                const dicData = column.dicData;
                const target = dicData.find((item) => item.value === value);
                this.form.categoryCode = (target && target.code) || '';
              }
            },
            span: 12,
            rules: [{ required: true, message: '请输入物料类别', trigger: 'blur' }]
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 12,
            rules: [{ required: true, message: '请输入物料编码', trigger: 'blur' }]
          },
          {
            label: '物料名称',
            prop: 'name',
            span: 12,
            rules: [{ required: true, message: '请输入物料名称', trigger: 'blur' }]
          },
          {
            label: '物料规格',
            prop: 'partSpec',
            span: 12,
            rules: [{ required: true, message: '请输入物料规格', trigger: 'blur' }]
          },
          {
            label: '单位',
            prop: 'uom',
            span: 12
          },
          {
            label: '保质期(天)',
            prop: 'expirationDays',
            type: 'number',
            min: 0,
            span: 12
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            span: 24
          }
        ];
      } else {
        this.formOption.column = [
          {
            label: '物料类型',
            prop: 'partType',
            type: 'select',
            hide: true,
            dicData: [],
            rules: [{ required: true, message: '请选择物料类型', trigger: 'blur' }]
          },
          {
            label: '物料类别',
            prop: 'categoryId',
            type: 'tree',
            dicData: [],
            props: {
              label: 'title',
              value: 'id'
            },
            change: ({ value, column }) => {
              if (value) {
                const dicData = column.dicData;
                const target = dicData.find((item) => item.value === value);
                this.form.categoryCode = (target && target.code) || '';
              }
            },
            span: 12,
            rules: [{ required: true, message: '请输入物料类别', trigger: 'blur' }]
          },
          {
            label: '产品编码',
            prop: 'partNo',
            span: 12,
            rules: [{ required: true, message: '请输入物料编码', trigger: 'blur' }]
          },
          {
            label: '产品名称',
            prop: 'name',
            span: 12,
            rules: [{ required: true, message: '请输入物料名称', trigger: 'blur' }]
          },
          {
            label: '产品型号',
            prop: 'partModel',
            span: 12,
            rules: [{ required: true, message: '请输入物料型号', trigger: 'blur' }]
          },
          {
            label: '产品规格',
            prop: 'partSpec',
            span: 12,
            rules: [{ required: true, message: '请输入物料规格', trigger: 'blur' }]
          },
          {
            label: '单价(元)',
            prop: 'unitPrice',
            type: 'number',
            min: 0,
            span: 12
          },
          {
            label: '单位',
            prop: 'uom',
            span: 12
          },
          {
            label: '保质期(天)',
            prop: 'expirationDays',
            type: 'number',
            min: 0,
            span: 12
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            span: 24
          }
        ];
        const partType = this.findObject(this.formOption.column, 'partType');
        getPartType().then((res) => {
          let data = this._get(res, 'data.data', []);
          partType.dicData = this._map(data, (item) => {
            return {
              label: item.dictValue,
              value: item.dictKey
            };
          });
        });
      }
      const formColumn = this.findObject(this.formOption.column, 'categoryId');
      formColumn.dicData = this.categories;
    },
    beforeClose(done) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleTabClick() {
      let partModel = this.findObject(this.option.column, 'partModel');
      if (this.activeName === 'material') {
        partModel.hide = true;
      } else {
        partModel.hide = false;
      }
      this.$refs.crud.searchReset();
      // this.page.currentPage = 1;
      // this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      console.log(this.activeName);
      console.log(this.query);
      if (this.activeName === 'material') {
        this.query['semifinished'] = false;
      } else {
        this.query['semifinished'] = true;
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 打开供应商选择模态框
     */
    openVendorCommonModal() {
      this.modalName = 'vendorModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 双击模态框行
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'vendorModal':
          this.brandInfoForm.vendorId = row.id;
          this.brandInfoForm.vendorCode = row.code;
          this.brandInfoForm.vendorName = row.name;
          break;
        default:
          break;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    brandBeforeOpen(done, type) {
      done();
    },
    brandRowSave(row, done, loading) {
      let obj = this._find(this.brandData, { partBrand: row.partBrand });
      if (!obj) {
        this.brandData.push(row);
        done();
      } else {
        this.$message.error('该物料品牌已存在，请勿重复填写！');
        loading();
      }
    },
    brandRowUpdate(row, index, done, loading) {
      this.brandData[index] = row;
      this.timer2 = new Date().getTime();
      done();
    },
    brandRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.brandData.splice(index, 1);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.custom-title {
  font-size: 16px;
  font-weight: bold;
  .mr10 {
    margin-right: 10px;
  }
}
</style>
